package cn.iocoder.yudao.module.els.dal.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.els.enums.ErrorCodeConstants.*;

/**
 * @Author cjc
 * @Date 2024/7/4 16:19
 * @Description: 编码生成器 redis
 * @Version 1.0
 */
@Repository
public class CodeGeneratorRedisDao {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String SERIAL_NO = "serial:%s:%s";

    /**
     * 递增
     * @param tenantKey TENANT key
     * @param businessKey BUSINESS key
     * @param delta 递增因子
     * @return 递增后的值
     */
    public Long incrSerialNoLongVal(String tenantKey,String businessKey,int delta){
       return stringRedisTemplate.opsForValue().increment(formatKey(SERIAL_NO,tenantKey,businessKey),delta);
    }

    public void expire(String tenantKey,String businessKey,Long timeout){
        stringRedisTemplate.expire(formatKey(SERIAL_NO,tenantKey,businessKey),timeout,TimeUnit.SECONDS);
    }

    /**
     * 格式化key值
     * @param redisKey Redis key
     * @param tenantKey Tenant key
     * @param businessKey Business key
     * @return after format key
     */
    public String formatKey(String redisKey,String tenantKey,String businessKey) {
        return String.format(redisKey, tenantKey,businessKey);
    }
}
